package org.dt.common.base;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Feng
 *
 */
public class Digests {

	private static MessageDigest getMd5Digest() throws NoSuchAlgorithmException {
		return MessageDigest.getInstance("MD5");
	}

	public static String md5OfString(String str)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest digest = getMd5Digest();
		digest.update(str.getBytes("UTF-8"));
		return Digitals.byte2Hex(digest.digest());
	}

	public static String md5OfFile(InputStream is) throws IOException,
			NoSuchAlgorithmException {
		MessageDigest digest = getMd5Digest();
		
		byte[] buffer = new byte[1024 * 256];
		int numRead = 0;
		while ((numRead = is.read(buffer)) > 0) {
			digest.update(buffer, 0, numRead);
		}
		return Digitals.byte2Hex(digest.digest());
	}

	public static String md5OfFile(String fileName)
			throws FileNotFoundException, IOException, NoSuchAlgorithmException {
		try (InputStream fis = new FileInputStream(fileName)) {
			return md5OfFile(fis);
		}
	}
}
